#include <gtest/gtest.h>
#include "common.h"

using namespace ::std;

// v01
// class Solution {
// public:
//     ListNode* swapPairs(ListNode* head) {
//         if(head == nullptr || head->next == nullptr) return head;
//         ListNode *pre = head, *cur = head->next, *post, *ret = head->next;
//         while(cur != nullptr) {
//             post = cur->next;
//             cur->next = pre;
//             if(post == nullptr) {
//                 pre->next = nullptr;
//                 break;
//             } else if(post->next == nullptr){
//                 pre->next = post;
//             } else pre->next = post->next;
//             pre = post;
//             cur = post->next;
//         }
//         return ret;
//     }
// };

class Solution {
public:
    ListNode* swapPairs(ListNode* head);
    ListNode* swapAdjacentPairs(ListNode* left, ListNode* right);
};

ListNode* Solution::swapPairs(ListNode* head) {
    if(nullptr == head || nullptr == head->next) return head;
    ListNode *pre, *left = head, *right = head->next; // pre用来辅助正确连接两个节点对
    head = right;
    while(right != nullptr) {
        pre = left;
        left = swapAdjacentPairs(left, right);
        left != nullptr ? right = left->next : right = nullptr;
        pre->next = right != nullptr ? right : left;
    }
    return head;
}

// 交换两个节点，并且返回两个节点的下一个节点
ListNode* Solution::swapAdjacentPairs(ListNode* left, ListNode* right) {
    left->next = right->next;
    right->next = left;
    return left->next;
}

class SwapPairsCheck : public ::testing::Test {
public:
	class Solution solution;
};

TEST_F(SwapPairsCheck, testSwapPairs_1) {
    vector<int> value = {1,2,3,4,5,6,7};
    printVector(value);
    ListNode* head = makeVecToList(value);
    head = solution.swapPairs(head);
    vector<int> out = makeListToVec(head);
    printVector(out);
    EXPECT_TRUE(vector<int>({2,1,4,3,6,5,7}) == out);
}

int main() {
	::testing::InitGoogleTest();
	return RUN_ALL_TESTS();
}